<?php
require 'lib/functions.php';

/* GET DATA FOR TEMPLATE */
require 'lib/arc/ARC_rdfxml_parser.php';

$request = ($_SERVER['REQUEST_URI'] == '/')?  'index.php' : substr($_SERVER['REQUEST_URI'], 1);

if(is_file($request))
{
	require $request;
	die();
}

$template = 'templates/'.($request);

$doc = new DOMDocument;

// We don't want to bother with white spaces
$doc->preserveWhiteSpace = false;

$doc->loadHTMLFile($template);

$xpath = new DOMXPath($doc);

$rdf_xml_link_els = $xpath->query("//link[@rel='alternate'][@type='application/rdf+xml']");

$rdf_triples = array();
foreach ($rdf_xml_link_els as $el)
{
	$args = array('base'=>$el->getAttribute('href'));
	$parser = new ARC_rdfxml_parser($args);
	$triples=@$parser->parse_data(file_get_contents($el->getAttribute('href')));
	$rdf_triples = array_merge($triples,$rdf_triples);
}


/* SET TEMPLATE VARIABLES */

/* get semantic template variables */
require 'lib/erdf/eRDF_parser.php';

$eRDF_parser = new eRDF_parser($template);
$eRDF_parser->parse();
$template_triples = $eRDF_parser->get_triples();

$data_triples = array();

foreach($rdf_triples as $t)
{
	$data_triples[]= array("s"=> $t['s']['uri'], "p"=>$t['p'], "o"=> ( (isset($t['o']['val']))? $t['o']['val'] : $t['o']['uri'] ) );
}

$variables = assign_variables($template_triples, $data_triples);

$x = 0;
foreach($template_triples as $t)
{
	$vars = array();
	
	foreach(array('s','p','o') as $n)
	{
		if(preg_match('/\$([a-zA-Z_0-9]+)/', $t[$n], $matches))
		{
			$var = $matches[1];
			
			$t[$n] = $var;
			$vars[]=$n;
		}
	}
	
	if($assoc_arr = match_triple($t,$vars, $rdf_triples))
	{
		 $variables = array_merge($assoc_arr, $variables);
	}

$x++;	
}

extract($variables);

// we pass the namespace prefixes that we want to use to this triples_to_resources function - 
// we use the prefixes that we define in the template, 
// not the ones  defined in the data RDF/XML

$eRDF_resources = triples_to_resources($template_triples, $eRDF_parser->get_schemas());
$resources = triples_to_resources($rdf_triples, $eRDF_parser->get_schemas());
require $template;
?>